<?php
namespace services\models;

/**
 * 添加到Solr中的商品信息
 *
 * @author huipeng.teng@liketry.com
 */
class SolrGoods extends \common\models\SolrGoods {
    /**
     * 获取主数据库的连接
     */
    public static function getDb() {
        return \Yii::$app->db;
    }

    /**
     * 获取从数据库的连接
     */
    public static function getSlaveDb() {
        return \Yii::$app->db;
    }

    /**
     * 通过商品ID获取信息
     * @param int $goods_id 商品ID
     * @return array 商品信息
     */
    public static function findByGoodsId($goods_id) {
        $var = self::find()->where('goods_id=:goods_id', [':goods_id' => $goods_id])->one();
        if(empty($var)) {
            return [];
        }

        return \yii\helpers\ArrayHelper::toArray($var);
    }

    /**
     * 查询指定数量的商品，刷新这些商品的索引。
     */
    public static function findGoods($count) {
        $vars = self::find()->limit($count)->all();
        if(empty($vars)) {
            return [];
        }

        return \yii\helpers\ArrayHelper::toArray($vars);
    }

    /**
     * 添加一个商品到solr_goods表
     * @param int $goods_id 商品ID
     */
    public static function add($goods_id) {
        if($goods_id < 1) {
            return false;
        }

        $goods_row = Goods::findByGoodsId($goods_id);// 商品显示状态，品牌ID，一级分类ID
        if(empty($goods_row)) {
            return false;
        }

        $goods_detail_row = GoodsDetail::findByGoodsId($goods_id, 'goods_name,register_date');// 商品名称，引进时间
        $goods_price_row = GoodsPrice::findByGoodsId($goods_id);// 商品4种价格

        // 获取商品的SKU基本信息
        $product_rows = self::getSlaveDb()
                ->createCommand('SELECT * FROM d_try.product WHERE goods_id = ' . $goods_id . ' AND STATUS = 0')
                ->queryAll();

        // 获取商品的SKU库存信息
        $product_stock_rows = self::getSlaveDb()
                ->createCommand('SELECT * FROM d_try.product_stock WHERE goods_id = ' . $goods_id)
                ->queryAll();

        if($goods_row['brand_id'] > 0) {
            $brand_row = BrandTable::findByBrandId($goods_row['brand_id'], 'brandname,q_index');
        }

        $product_id_list = array();
        $price = $try_price = 0;
        $buy_status = $try_status = $buy_try_status = $sale_num = $stock = 0;
        $buy_status_new = $try_status_new = $buy_try_status_new = 0;

        foreach($product_rows as $row) {
            // 试用类型SKU
            if($row['type'] == 1 && $row['sale_status'] == 1) {
                if($row['default_sku'] == 1) {
                    $try_status = 1;// 商品是否可以试用，以默认SKU的试用状态为判断依据。
                    $default_sku_try_price = ($row['price_type'] == 0 ? $row['sale_price'] : $row['try_price'] / 100);
                    $try_price = $row['try_price'];
                }
            }

            // 购买类型SKU
            if($row['type'] == 2 && $row['sale_status'] == 1) {
                if($row['default_sku'] == 1) {
                    $buy_status = 1;// 商品是否可以购买，以默认SKU的购买状态为判断依据。
                    $default_sku_sale_price = ($row['price_type'] == 0 ? $row['sale_price'] : $row['try_price'] / 100);
                }
            }

            // 保存上架状态的SKU ID
            if($row['sale_status'] == 1) {
                $product_id_list[] = $row['product_id'];
            }
        }

        // 可以购买，可以试用。
        if($buy_status == 1 && $try_status == 1) {
            $buy_status_new = 0;
            $try_status_new = 0;
            $buy_try_status_new = 1;
        }
        // 可以购买，不能试用。
        if($buy_status == 1 && $try_status == 0) {
            $buy_status_new = 1;
            $try_status_new = 0;
        }
        // 不能购买，可以试用
        if($buy_status == 0 && $try_status == 1) {
            $buy_status_new = 0;
            $try_status_new = 1;
        }

        // 如果开启了销售类型的RMB价格，则优先使用销售的RMB价格值。
        /*if($buy_status == 1 && $goods_price_row['sale_price_type'] == 0) {
            $price = $goods_price_row['sale_price_rmb'];
        }*/
        // 如果没有开启销售类型的RMB价格，则使用试用类型的RMB价格值。
        /*if($price === '' && $try_status == 1 && $goods_price_row['try_price_type'] == 0) {
            $price = $goods_price_row['try_price_rmb'];
        }*/

        // 如果开启了试用类型的试豆价格，则优先使用试豆的价格值。
        /*if($try_status == 1 && $goods_price_row['try_price_type'] == 1) {
            $try_price = $goods_price_row['try_price_score'];
        }*/
        // 如果没有开启试用类型的试豆价格，则使用销售类型的试豆价格值。
        /*if($try_price === '' && $buy_status == 1 && $goods_price_row['sale_price_type'] == 1) {
            $try_price = $goods_price_row['sale_price_score'];
        }*/

        // 有RMB价格则使用RMB价格，没有RMB价格则把试豆价格转换为RMB价格（1元 = 100试豆）。
        if(isset($default_sku_sale_price)) {
            $price = $default_sku_sale_price;
        } elseif(isset($default_sku_try_price)) {
            $price = $default_sku_try_price;
        } elseif($buy_status == 1 && $goods_price_row['sale_price_type'] == 0) {
            $price = $goods_price_row['sale_price_rmb'];
        } elseif($try_status == 1 && $goods_price_row['try_price_type'] == 0) {
            $price = $goods_price_row['try_price_rmb'];
        } elseif($buy_status == 1 && $goods_price_row['sale_price_type'] == 1) {
            $price = $goods_price_row['sale_price_score'] / 100;
        }elseif($try_status == 1 && $goods_price_row['try_price_type'] == 1) {
            $price = $goods_price_row['try_price_score'] / 100;
        }

        // 库存和销售数量
        foreach($product_stock_rows as $row) {
            // 只计算上架状态的SKU的库存
            if(in_array($row['product_id'], $product_id_list)) {
                $stock += $row['stock'];
            }

            // 计算上架和下架状态的SKU的销售数量
            $sale_num += $row['sale_num'];
        }

        self::deleteAll('goods_id = :goods_id', ['goods_id' => $goods_id]);

        $solrGoods = new \common\models\SolrGoods();
        $solrGoods->goods_id = $goods_id;
        $solrGoods->brand_id = $goods_row['brand_id'];
        if(isset($brand_row) && !empty($brand_row['q_index'])) {
            $solrGoods->brand_index = $brand_row['q_index'];
            $solrGoods->brand_name = $brand_row['brandname'];
        }
        $solrGoods->create_time = date('Y-m-d H:i:s', $goods_detail_row['register_date']);
        $solrGoods->goods_name = $goods_detail_row['goods_name'];
        $solrGoods->price = $price;
        $solrGoods->try_price = $try_price;
        $solrGoods->buy_status = $buy_status_new;
        $solrGoods->try_status = $try_status_new;
        $solrGoods->buy_try_status = $buy_try_status_new;
        $solrGoods->sale_num = $sale_num;
        $solrGoods->stock = $stock;
        $solrGoods->status = $goods_row['status'];
        $solrGoods->category_1 = $goods_row['category_1'];
        $solrGoods->save();

        unset($goods_row, $goods_detail_row, $goods_price_row, $product_rows, $product_stock_rows);
    }

    /**
     * 定时添加最近一分钟销售的商品的库存到Solr索引中
     */
    public static function addStockSolrIndex() {
        // 获取最近一分钟销售的商品信息
        $sql = "select distinct goods_id from d_try.order_goods "
                . "where create_time >= '" . date('Y-m-d H:i:s', time() - 60) 
                . "' and create_time <= '" . date('Y-m-d H:i:s') . "' limit 5000";

        $order_goods_rows = self::getSlaveDb()->createCommand($sql)->queryAll();
        if(empty($order_goods_rows)) {
            return false;
        }

        foreach($order_goods_rows as $row) {
            self::add($row['goods_id']);
        }
    }
}
